package cn.lvji.sus.db;

import cn.lvji.sus.Config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接工厂
 *
 * @author zhouzx
 */
public class ConnectionFactory {
    private static HikariDataSource hikariDataSource;

    static {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(Config.getConfig("db.url"));
        config.setUsername(Config.getConfig("db.username"));
        config.setPassword(Config.getConfig("db.password"));
        config.setDriverClassName("com.mysql.jdbc.Driver");
        config.setIdleTimeout(Config.getLongConfig("db.idle.timeout"));
        config.setMaximumPoolSize(Config.getIntConfig("db.max.poolsize"));
        config.setMinimumIdle(Config.getIntConfig("db.min.idle"));
        config.setMaxLifetime(Config.getLongConfig("db.max.lifetime"));
        config.setConnectionTimeout(Config.getLongConfig("db.connection.timeout"));
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

        hikariDataSource = new HikariDataSource(config);
    }

    public static Connection getConnection() throws SQLException {
        return hikariDataSource.getConnection();
    }
}
